(function($){
	
	$(function(){

		var controls = null;
		var controlsPrev = null;
		var controlsNext = null;
		var controlsClose = null;

		var gallery = $("<div id='osmio-modal-gallery'></div>").appendTo("body");

		gallery.osmioModal({
			padding: [40, 40, 120, 40],
			minWidth: 100,
			minHeight: 100
		});
		
		gallery.osmioModalMedia();

		gallery.osmioModal("exec", function(modal){

			//console.dir(modal.options);

			modal.elements.wrapper.append("<ul id='osmio-modal-gallery-controls'><li><a href='#' rel='prev'>&lsaquo; Назад</a></li><li><a href='#' rel='close'>&times; Закрыть</a></li><li><a href='#' rel='next'>Вперед &rsaquo;</a></li></ul>")

			controls = $("#osmio-modal-gallery-controls");
			controlsPrev = controls.find("a[rel=prev]");
			controlsNext = controls.find("a[rel=next]");
			controlsClose = controls.find("a[rel=close]");

			controlsClose.click(function(){
				gallery.osmioModal("close");
			});

			$("a.osmio-modal-gallery").click(function(e){

				e.preventDefault();

				var self = $(this);

				$("#osmio-modal-gallery").osmioModalMedia(self.attr("href"), self.attr("title"), self.attr("link"));

				var links = $("a.osmio-modal-gallery").filter("a[rel=" + self.attr("rel") + "]").data("osmio-modal-gallery-current", false);
				self.data("osmio-modal-gallery-current", true);

				var prev = false;
				var next = false;
				var nextCatch = false;
				var prevCatch = false;

				links.each(function(){

					if (nextCatch) next = $(this);

					if ($(this).data("osmio-modal-gallery-current")) {

						nextCatch = true;
						prev = prevCatch;

					} else {


						nextCatch = false;
					}

					prevCatch = $(this);

				});

				controlsPrev.unbind("click");
				controlsNext.unbind("click");

				if (prev) {

					controlsPrev.removeClass("osmio-modal-gallery-controls-disabled").click(function(e){
						e.preventDefault();
						if (!$(this).hasClass("osmio-modal-gallery-controls-disabled")) prev.click();
					})

				} else {

					controlsPrev.addClass("osmio-modal-gallery-controls-disabled");

				}

				if (next) {

					controlsNext.removeClass("osmio-modal-gallery-controls-disabled").click(function(e){
						e.preventDefault();
						if (!$(this).hasClass("osmio-modal-gallery-controls-disabled")) next.click();
					})

				} else {

					controlsNext.addClass("osmio-modal-gallery-controls-disabled");

				}

				return false;

			});

		});

	});

})(jQuery);